<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>班级学生管理系统</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  <style>
    body {
      font-family: 'Microsoft YaHei', sans-serif;
      background-color: #f8f9fa;
    }
    .sidebar {
      min-height: 100vh;
      background-color: #343a40;
      color: white;
    }
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.8);
      margin-bottom: 5px;
    }
    .sidebar .nav-link:hover {
      color: white;
      background-color: rgba(255, 255, 255, 0.1);
    }
    .sidebar .nav-link.active {
      color: white;
      background-color: #007bff;
    }
    .main-content {
      padding: 20px;
    }
    .card {
      margin-bottom: 20px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }
    .avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      object-fit: cover;
    }
    .table th {
      background-color: #f8f9fa;
    }
    .search-box {
      max-width: 300px;
    }
    .class-card {
      transition: transform 0.3s;
    }
    .class-card:hover {
      transform: translateY(-5px);
    }
  </style>
</head>
<body>
<div class="container-fluid">
  <div class="row">
    <!-- 侧边栏 -->
    <div class="col-md-2 sidebar p-0">
      <div class="p-3">
        <h4 class="text-center mb-4">班级管理系统</h4>
        <ul class="nav flex-column">
          <li class="nav-item">
            <a class="nav-link active" href="#dashboard" data-bs-toggle="tab">
              <i class="bi bi-speedometer2 me-2"></i>仪表盘
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#classes" data-bs-toggle="tab">
              <i class="bi bi-people-fill me-2"></i>班级管理
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#students" data-bs-toggle="tab">
              <i class="bi bi-person-lines-fill me-2"></i>学生管理
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#statistics" data-bs-toggle="tab">
              <i class="bi bi-graph-up me-2"></i>数据统计
            </a>
          </li>
        </ul>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="col-md-10 main-content">
      <div class="tab-content">
        <!-- 仪表盘 -->
        <div class="tab-pane fade show active" id="dashboard">
          <h3 class="mb-4">系统概览</h3>
          <div class="row">
            <div class="col-md-4">
              <div class="card bg-primary text-white">
                <div class="card-body">
                  <h5 class="card-title">班级总数</h5>
                  <h2 id="total-classes" class="card-text">3</h2>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="card bg-success text-white">
                <div class="card-body">
                  <h5 class="card-title">学生总数</h5>
                  <h2 id="total-students" class="card-text">4</h2>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="card bg-info text-white">
                <div class="card-body">
                  <h5 class="card-title">平均年龄</h5>
                  <h2 id="avg-age" class="card-text">20</h2>
                </div>
              </div>
            </div>
          </div>

          <div class="row mt-4">
            <div class="col-md-6">
              <div class="card">
                <div class="card-header">
                  <h5>班级人数分布</h5>
                </div>
                <div class="card-body">
                  <canvas id="classDistributionChart" height="250"></canvas>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="card">
                <div class="card-header">
                  <h5>性别比例</h5>
                </div>
                <div class="card-body">
                  <canvas id="genderDistributionChart" height="250"></canvas>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 班级管理 -->
        <div class="tab-pane fade" id="classes">
          <div class="d-flex justify-content-between align-items-center mb-4">
            <h3>班级管理</h3>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addClassModal">
              <i class="bi bi-plus-lg"></i> 添加班级
            </button>
          </div>

          <div class="row" id="class-list">
            <!-- 班级卡片将通过JS动态加载 -->
          </div>
        </div>

        <!-- 学生管理 -->
        <div class="tab-pane fade" id="students">
          <div class="d-flex justify-content-between align-items-center mb-4">
            <h3>学生管理</h3>
            <div>
              <div class="input-group search-box">
                <input type="text" class="form-control" placeholder="搜索学生..." id="student-search">
                <button class="btn btn-outline-secondary" type="button" id="search-student">
                  <i class="bi bi-search"></i>
                </button>
              </div>
            </div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addStudentModal">
              <i class="bi bi-plus-lg"></i> 添加学生
            </button>
          </div>

          <div class="card">
            <div class="card-body">
              <table class="table table-hover">
                <thead>
                <tr>
                  <th>ID</th>
                  <th>头像</th>
                  <th>姓名</th>
                  <th>性别</th>
                  <th>年龄</th>
                  <th>班级</th>
                  <th>联系方式</th>
                  <th>操作</th>
                </tr>
                </thead>
                <tbody id="student-table-body">
                <!-- 学生数据将通过JS动态加载 -->
                </tbody>
              </table>
              <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="student-pagination">
                  <!-- 分页将通过JS动态加载 -->
                </ul>
              </nav>
            </div>
          </div>
        </div>

        <!-- 数据统计 -->
        <div class="tab-pane fade" id="statistics">
          <h3 class="mb-4">数据统计</h3>
          <div class="row">
            <div class="col-md-6">
              <div class="card">
                <div class="card-header">
                  <h5>各班级人数统计</h5>
                </div>
                <div class="card-body">
                  <canvas id="classSizeChart" height="300"></canvas>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="card">
                <div class="card-header">
                  <h5>年龄分布</h5>
                </div>
                <div class="card-body">
                  <canvas id="ageDistributionChart" height="300"></canvas>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 添加班级模态框 -->
<div class="modal fade" id="addClassModal" tabindex="-1" aria-labelledby="addClassModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addClassModalLabel">添加班级</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="add-class-form">
          <div class="mb-3">
            <label for="class-name" class="form-label">班级名称</label>
            <input type="text" class="form-control" id="class-name" required>
          </div>
          <div class="mb-3">
            <label for="class-teacher" class="form-label">班主任</label>
            <input type="text" class="form-control" id="class-teacher">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="save-class-btn">保存</button>
      </div>
    </div>
  </div>
</div>

<!-- 添加学生模态框 -->
<div class="modal fade" id="addStudentModal" tabindex="-1" aria-labelledby="addStudentModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addStudentModalLabel">添加学生</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="add-student-form">
          <div class="mb-3">
            <label for="student-name" class="form-label">学生姓名</label>
            <input type="text" class="form-control" id="student-name" required>
          </div>
          <div class="mb-3">
            <label class="form-label">性别</label>
            <div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="gender" id="male" value="男" checked>
                <label class="form-check-label" for="male">男</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="gender" id="female" value="女">
                <label class="form-check-label" for="female">女</label>
              </div>
            </div>
          </div>
          <div class="mb-3">
            <label for="age" class="form-label">年龄</label>
            <input type="number" class="form-control" id="age">
          </div>
          <div class="mb-3">
            <label for="phone" class="form-label">联系电话</label>
            <input type="tel" class="form-control" id="phone">
          </div>
          <div class="mb-3">
            <label for="email" class="form-label">电子邮箱</label>
            <input type="email" class="form-control" id="email">
          </div>
          <div class="mb-3">
            <label for="address" class="form-label">家庭住址</label>
            <input type="text" class="form-control" id="address">
          </div>
          <div class="mb-3">
            <label for="class-select" class="form-label">所属班级</label>
            <select class="form-select" id="class-select">
              <option value="">-- 请选择班级 --</option>
              <!-- 班级选项将通过JS动态加载 -->
            </select>
          </div>
          <div class="mb-3">
            <label for="avatar" class="form-label">头像</label>
            <input type="file" class="form-control" id="avatar">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="save-student-btn">保存</button>
      </div>
    </div>
  </div>
</div>

<!-- 编辑学生模态框 -->
<div class="modal fade" id="editStudentModal" tabindex="-1" aria-labelledby="editStudentModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editStudentModalLabel">编辑学生信息</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="edit-student-form">
          <input type="hidden" id="edit-student-id">
          <div class="mb-3">
            <label for="edit-student-name" class="form-label">学生姓名</label>
            <input type="text" class="form-control" id="edit-student-name" required>
          </div>
          <div class="mb-3">
            <label class="form-label">性别</label>
            <div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="edit-gender" id="edit-male" value="男">
                <label class="form-check-label" for="edit-male">男</label>
              </div>
              <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="edit-gender" id="edit-female" value="女">
                <label class="form-check-label" for="edit-female">女</label>
              </div>
            </div>
          </div>
          <div class="mb-3">
            <label for="edit-age" class="form-label">年龄</label>
            <input type="number" class="form-control" id="edit-age">
          </div>
          <div class="mb-3">
            <label for="edit-phone" class="form-label">联系电话</label>
            <input type="tel" class="form-control" id="edit-phone">
          </div>
          <div class="mb-3">
            <label for="edit-email" class="form-label">电子邮箱</label>
            <input type="email" class="form-control" id="edit-email">
          </div>
          <div class="mb-3">
            <label for="edit-address" class="form-label">家庭住址</label>
            <input type="text" class="form-control" id="edit-address">
          </div>
          <div class="mb-3">
            <label for="edit-class-select" class="form-label">所属班级</label>
            <select class="form-select" id="edit-class-select">
              <option value="">-- 请选择班级 --</option>
              <!-- 班级选项将通过JS动态加载 -->
            </select>
          </div>
          <div class="mb-3">
            <label for="edit-avatar" class="form-label">头像</label>
            <input type="file" class="form-control" id="edit-avatar">
            <div class="mt-2">
              <img id="current-avatar" src="" class="avatar" alt="当前头像">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="update-student-btn">更新</button>
      </div>
    </div>
  </div>
</div>

<!-- 脚本 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  $(document).ready(function() {
    // 模拟数据
    const classes = [
      { class_id: 1, class_name: '计算机科学与技术1班', class_teacher: '张老师', class_size: 2 },
      { class_id: 2, class_name: '软件工程2班', class_teacher: '李老师', class_size: 1 },
      { class_id: 3, class_name: '人工智能3班', class_teacher: '王老师', class_size: 1 }
    ];

    const students = [
      { student_id: 1, student_name: '张三', gender: '男', age: 20, phone: '13800138001',
        email: 'zhangsan@example.com', address: '北京市海淀区', class_id: 1, avatar: null },
      { student_id: 2, student_name: '李四', gender: '女', age: 19, phone: '13800138002',
        email: 'lisi@example.com', address: '上海市浦东新区', class_id: 1, avatar: null },
      { student_id: 3, student_name: '王五', gender: '男', age: 21, phone: '13800138003',
        email: 'wangwu@example.com', address: '广州市天河区', class_id: 2, avatar: null },
      { student_id: 4, student_name: '赵六', gender: '女', age: 20, phone: '13800138004',
        email: 'zhaoliu@example.com', address: '深圳市南山区', class_id: 3, avatar: null }
    ];

    // 初始化仪表盘数据
    updateDashboard();

    // 加载班级列表
    loadClassList();

    // 加载学生列表
    loadStudentList();

    // 初始化图表
    initCharts();

    // 添加班级按钮点击事件
    $('#save-class-btn').click(function() {
      const className = $('#class-name').val();
      const classTeacher = $('#class-teacher').val();

      if (!className) {
        alert('请输入班级名称');
        return;
      }

      // 模拟添加班级
      const newClass = {
        class_id: classes.length + 1,
        class_name: className,
        class_teacher: classTeacher,
        class_size: 0
      };

      classes.push(newClass);
      $('#addClassModal').modal('hide');
      loadClassList();
      updateDashboard();

      // 重置表单
      $('#add-class-form')[0].reset();
    });

    // 添加学生按钮点击事件
    $('#save-student-btn').click(function() {
      const studentName = $('#student-name').val();
      const gender = $('input[name="gender"]:checked').val();
      const age = $('#age').val();
      const phone = $('#phone').val();
      const email = $('#email').val();
      const address = $('#address').val();
      const classId = $('#class-select').val();

      if (!studentName) {
        alert('请输入学生姓名');
        return;
      }

      if (!classId) {
        alert('请选择班级');
        return;
      }

      // 模拟添加学生
      const newStudent = {
        student_id: students.length + 1,
        student_name: studentName,
        gender: gender,
        age: age ? parseInt(age) : null,
        phone: phone,
        email: email,
        address: address,
        class_id: parseInt(classId),
        avatar: null
      };

      students.push(newStudent);

      // 更新班级人数
      const classIndex = classes.findIndex(c => c.class_id == classId);
      if (classIndex !== -1) {
        classes[classIndex].class_size++;
      }

      $('#addStudentModal').modal('hide');
      loadStudentList();
      loadClassList();
      updateDashboard();

      // 重置表单
      $('#add-student-form')[0].reset();
    });

    // 搜索学生
    $('#search-student').click(function() {
      loadStudentList();
    });

    $('#student-search').keypress(function(e) {
      if (e.which === 13) {
        loadStudentList();
      }
    });

    // 编辑学生按钮点击事件
    $('#update-student-btn').click(function() {
      const studentId = $('#edit-student-id').val();
      const studentName = $('#edit-student-name').val();
      const gender = $('input[name="edit-gender"]:checked').val();
      const age = $('#edit-age').val();
      const phone = $('#edit-phone').val();
      const email = $('#edit-email').val();
      const address = $('#edit-address').val();
      const classId = $('#edit-class-select').val();

      if (!studentName) {
        alert('请输入学生姓名');
        return;
      }

      if (!classId) {
        alert('请选择班级');
        return;
      }

      // 模拟更新学生
      const studentIndex = students.findIndex(s => s.student_id == studentId);
      if (studentIndex !== -1) {
        const oldClassId = students[studentIndex].class_id;

        // 更新学生信息
        students[studentIndex] = {
          ...students[studentIndex],
          student_name: studentName,
          gender: gender,
          age: age ? parseInt(age) : null,
          phone: phone,
          email: email,
          address: address,
          class_id: parseInt(classId)
        };

        // 如果班级变更，更新班级人数
        if (oldClassId != classId) {
          const oldClassIndex = classes.findIndex(c => c.class_id == oldClassId);
          if (oldClassIndex !== -1) {
            classes[oldClassIndex].class_size--;
          }

          const newClassIndex = classes.findIndex(c => c.class_id == classId);
          if (newClassIndex !== -1) {
            classes[newClassIndex].class_size++;
          }
        }

        $('#editStudentModal').modal('hide');
        loadStudentList();
        loadClassList();
        updateDashboard();
      }
    });

    // 初始化班级选择下拉框
    function initClassSelects() {
      $('#class-select, #edit-class-select').empty();
      $('#class-select, #edit-class-select').append('<option value="">-- 请选择班级 --</option>');

      classes.forEach(cls => {
        $('#class-select, #edit-class-select').append(
                `<option value="${cls.class_id}">${cls.class_name}</option>`
        );
      });
    }

    // 加载班级列表
    function loadClassList() {
      $('#class-list').empty();

      classes.forEach(cls => {
        $('#class-list').append(`
                        <div class="col-md-4">
                            <div class="card class-card">
                                <div class="card-body">
                                    <h5 class="card-title">${cls.class_name}</h5>
                                    <p class="card-text">
                                        <i class="bi bi-person-fill"></i> 班主任: ${cls.class_teacher || '未设置'}<br>
                                        <i class="bi bi-people-fill"></i> 学生人数: ${cls.class_size}
                                    </p>
                                    <div class="d-flex justify-content-between">
                                        <button class="btn btn-sm btn-outline-primary view-class-btn" data-id="${cls.class_id}">
                                            <i class="bi bi-eye"></i> 查看
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete-class-btn" data-id="${cls.class_id}">
                                            <i class="bi bi-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);
      });

      // 查看班级按钮点击事件
      $('.view-class-btn').click(function() {
        const classId = $(this).data('id');
        // 这里可以跳转到班级详情页或过滤学生列表
        alert(`查看班级ID: ${classId}`);
      });

      // 删除班级按钮点击事件
      $('.delete-class-btn').click(function() {
        const classId = $(this).data('id');
        if (confirm('确定要删除这个班级吗？')) {
          // 检查班级是否有学生
          const hasStudents = students.some(s => s.class_id == classId);
          if (hasStudents) {
            alert('该班级还有学生，不能删除！');
            return;
          }

          // 模拟删除班级
          const index = classes.findIndex(c => c.class_id == classId);
          if (index !== -1) {
            classes.splice(index, 1);
            loadClassList();
            updateDashboard();
          }
        }
      });

      initClassSelects();
    }

    // 加载学生列表
    function loadStudentList(page = 1, pageSize = 5) {
      const searchTerm = $('#student-search').val().toLowerCase();

      // 过滤学生
      let filteredStudents = students;
      if (searchTerm) {
        filteredStudents = students.filter(s =>
                s.student_name.toLowerCase().includes(searchTerm) ||
                (s.phone && s.phone.includes(searchTerm)) ||
                (s.email && s.email.toLowerCase().includes(searchTerm))
        );
      }

      // 分页
      const totalStudents = filteredStudents.length;
      const totalPages = Math.ceil(totalStudents / pageSize);
      const paginatedStudents = filteredStudents.slice((page - 1) * pageSize, page * pageSize);

      // 渲染学生表格
      $('#student-table-body').empty();

      paginatedStudents.forEach(student => {
        const cls = classes.find(c => c.class_id == student.class_id);
        const className = cls ? cls.class_name : '未分配班级';

        $('#student-table-body').append(`
                        <tr>
                            <td>${student.student_id}</td>
                            <td>
                                <img src="${student.avatar || 'https://via.placeholder.com/50'}" class="avatar" alt="${student.student_name}">
                            </td>
                            <td>${student.student_name}</td>
                            <td>${student.gender}</td>
                            <td>${student.age || '-'}</td>
                            <td>${className}</td>
                            <td>${student.phone || '-'}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary edit-student-btn" data-id="${student.student_id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-student-btn" data-id="${student.student_id}">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `);
      });

      // 渲染分页
      $('#student-pagination').empty();

      if (totalPages > 1) {
        // 上一页按钮
        $('#student-pagination').append(`
                        <li class="page-item ${page === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="#" data-page="${page - 1}">上一页</a>
                        </li>
                    `);

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
          $('#student-pagination').append(`
                            <li class="page-item ${i === page ? 'active' : ''}">
                                <a class="page-link" href="#" data-page="${i}">${i}</a>
                            </li>
                        `);
        }

        // 下一页按钮
        $('#student-pagination').append(`
                        <li class="page-item ${page === totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="#" data-page="${page + 1}">下一页</a>
                        </li>
                    `);

        // 分页按钮点击事件
        $('.page-link').click(function(e) {
          e.preventDefault();
          const newPage = $(this).data('page');
          loadStudentList(newPage, pageSize);
        });
      }

      // 编辑学生按钮点击事件
      $('.edit-student-btn').click(function() {
        const studentId = $(this).data('id');
        const student = students.find(s => s.student_id == studentId);

        if (student) {
          $('#edit-student-id').val(student.student_id);
          $('#edit-student-name').val(student.student_name);
          $(`input[name="edit-gender"][value="${student.gender}"]`).prop('checked', true);
          $('#edit-age').val(student.age || '');
          $('#edit-phone').val(student.phone || '');
          $('#edit-email').val(student.email || '');
          $('#edit-address').val(student.address || '');
          $('#edit-class-select').val(student.class_id || '');
          $('#current-avatar').attr('src', student.avatar || 'https://via.placeholder.com/50');

          $('#editStudentModal').modal('show');
        }
      });

      // 删除学生按钮点击事件
      $('.delete-student-btn').click(function() {
        const studentId = $(this).data('id');
        if (confirm('确定要删除这个学生吗？')) {
          // 模拟删除学生
          const index = students.findIndex(s => s.student_id == studentId);
          if (index !== -1) {
            const classId = students[index].class_id;
            students.splice(index, 1);

            // 更新班级人数
            const classIndex = classes.findIndex(c => c.class_id == classId);
            if (classIndex !== -1) {
              classes[classIndex].class_size--;
            }

            loadStudentList();
            loadClassList();
            updateDashboard();
          }
        }
      });
    }

    // 更新仪表盘数据
    function updateDashboard() {
      $('#total-classes').text(classes.length);
      $('#total-students').text(students.length);

      // 计算平均年龄
      const ages = students.map(s => s.age).filter(age => age);
      const avgAge = ages.length > 0 ? (ages.reduce((a, b) => a + b, 0) / ages.length).toFixed(1) : 0;
      $('#avg-age').text(avgAge);

      // 更新图表
      updateCharts();
    }

    // 初始化图表
    function initCharts() {
      // 班级人数分布图
      const classCtx = document.getElementById('classDistributionChart').getContext('2d');
      window.classDistributionChart = new Chart(classCtx, {
        type: 'bar',
        data: {
          labels: classes.map(c => c.class_name),
          datasets: [{
            label: '学生人数',
            data: classes.map(c => c.class_size),
            backgroundColor: 'rgba(54, 162, 235, 0.5)',
            borderColor: 'rgba(54, 162, 235, 1)',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });

      // 性别比例图
      const genderCtx = document.getElementById('genderDistributionChart').getContext('2d');
      window.genderDistributionChart = new Chart(genderCtx, {
        type: 'pie',
        data: {
          labels: ['男', '女'],
          datasets: [{
            data: [
              students.filter(s => s.gender === '男').length,
              students.filter(s => s.gender === '女').length
            ],
            backgroundColor: [
              'rgba(54, 162, 235, 0.5)',
              'rgba(255, 99, 132, 0.5)'
            ],
            borderColor: [
              'rgba(54, 162, 235, 1)',
              'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true
        }
      });

      // 各班级人数统计图
      const classSizeCtx = document.getElementById('classSizeChart').getContext('2d');
      window.classSizeChart = new Chart(classSizeCtx, {
        type: 'doughnut',
        data: {
          labels: classes.map(c => c.class_name),
          datasets: [{
            data: classes.map(c => c.class_size),
            backgroundColor: [
              'rgba(255, 99, 132, 0.5)',
              'rgba(54, 162, 235, 0.5)',
              'rgba(255, 206, 86, 0.5)'
            ],
            borderColor: [
              'rgba(255, 99, 132, 1)',
              'rgba(54, 162, 235, 1)',
              'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true
        }
      });

      // 年龄分布图
      const ageCtx = document.getElementById('ageDistributionChart').getContext('2d');
      window.ageDistributionChart = new Chart(ageCtx, {
        type: 'line',
        data: {
          labels: ['18岁', '19岁', '20岁', '21岁', '22岁'],
          datasets: [{
            label: '学生人数',
            data: [0, 0, 0, 0, 0], // 初始化为0，后面会更新
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderColor: 'rgba(75, 192, 192, 1)',
            borderWidth: 2,
            tension: 0.1,
            fill: true
          }]
        },
        options: {
          responsive: true,
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }

    // 更新图表数据
    function updateCharts() {
      // 更新班级人数分布图
      window.classDistributionChart.data.datasets[0].data = classes.map(c => c.class_size);
      window.classDistributionChart.update();

      // 更新性别比例图
      window.genderDistributionChart.data.datasets[0].data = [
        students.filter(s => s.gender === '男').length,
        students.filter(s => s.gender === '女').length
      ];
      window.genderDistributionChart.update();

      // 更新各班级人数统计图
      window.classSizeChart.data.datasets[0].data = classes.map(c => c.class_size);
      window.classSizeChart.update();

      // 更新年龄分布图
      const ageCounts = {
        18: 0,
        19: 0,
        20: 0,
        21: 0,
        22: 0
      };

      students.forEach(s => {
        if (s.age && ageCounts.hasOwnProperty(s.age)) {
          ageCounts[s.age]++;
        }
      });

      window.ageDistributionChart.data.datasets[0].data = [
        ageCounts[18],
        ageCounts[19],
        ageCounts[20],
        ageCounts[21],
        ageCounts[22]
      ];
      window.ageDistributionChart.update();
    }
  });
</script>
</body>
</html>